package com.smart.upload.interceptor;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.smart.upload.bean.UserInfo;
import com.smart.upload.util.UploadSessionUtil;
import com.ydcycloud.sys.model.SessionUser;

/**
 * <b>Description:文件上传工具类</b><br>
 * @author 唐海洋
 * @version 1.0 2016-9-25 下午3:02:44
 */
public class UploadHandlerInterceptor extends HandlerInterceptorAdapter {
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		
		HttpSession httpSession=request.getSession();		
		SessionUser sessionUser=(SessionUser) httpSession.getAttribute("session_user");
		
		if(sessionUser==null){
			UploadSessionUtil.setUserInfo(new UserInfo("未登录用户", "", "share"));
		}else{
			UploadSessionUtil.setUserInfo(new UserInfo(sessionUser.getName(), sessionUser.getName(), sessionUser.getId()));
		}
		
		UploadSessionUtil.setQueryParams(getUserParams(request));
		return true;// 继续流程
	}
	
	/**
	 * Description:通过解析http请求头信息，获取用户提交上来的所有参数
	 * @author 唐海洋
	 * @Version 1.0 2016-8-5上午11:03:16 
	 * @return 用户提交的参数
	 */
	private Map<String, Object> getUserParams(HttpServletRequest httpServletRequest){
		
		Map<String, Object> r=new HashMap<String, Object>();
		Enumeration<String> parameterNamesEnumeration=httpServletRequest.getParameterNames();
		while (parameterNamesEnumeration.hasMoreElements()) {
			String parameterName= parameterNamesEnumeration.nextElement();
			if(!"file".equals(parameterName)){
				String[] parameterValues=httpServletRequest.getParameterValues(parameterName);
				if(parameterValues!=null && parameterValues.length>0){
					r.put(parameterName, parameterValues);
				}
			}
		}
		return r;
	}

}